import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios' // 新增：导入axios
import ElementPlus, { ElMessage } from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'

const app = createApp(App)

// 1. 注册Element Plus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}

// 2. 配置Element Plus中文
app.use(ElementPlus, { locale: zhCn }).use(store).use(router)

// 3. 全局axios配置（新增部分）
axios.defaults.baseURL = 'http://localhost:9190' // 设置后端API基础地址
axios.defaults.withCredentials = true // 允许携带Cookie

// 请求拦截器：自动添加Token
axios.interceptors.request.use(config => {
    const token = localStorage.getItem('token')
    if (token) {
        config.headers.Authorization = `Bearer ${token}` // Bearer Token格式
    }
    return config
})

// 响应拦截器：处理Token过期
axios.interceptors.response.use(
    response => response,
    error => {
        if (error.response?.status === 401) {
            localStorage.removeItem('token')
            router.push('/login') // 跳转到登录页
            ElMessage.error('登录已过期，请重新登录') // 使用Element Plus的提示
        }
        return Promise.reject(error)
    }
)

// 4. 将axios挂载到全局（替代原来的BASE_URL）
app.config.globalProperties.$axios = axios // 组件内通过 this.$axios 使用
window.axios = axios // 全局通过 window.axios 使用

// 5. 解决ResizeObserver报错（原有代码）
const debounce = (fn, delay) => {
    let timer = null
    return function () {
        let context = this
        let args = arguments
        clearTimeout(timer)
        timer = setTimeout(function () {
            fn.apply(context, args)
        }, delay)
    }
}
const _ResizeObserver = window.ResizeObserver
window.ResizeObserver = class ResizeObserver extends _ResizeObserver {
    constructor(callback) {
        callback = debounce(callback, 16)
        super(callback)
    }
}

// 6. 全局方法（原有代码）
window.getUser = () => {
    return localStorage.user ? JSON.parse(localStorage.user) : null
}
window.getJobId = () => {
    return localStorage.jobId ? JSON.parse(localStorage.jobId) : null
}



router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('token');
    if (to.meta.requiresAuth && !token) {
        next('/login');
    } else {
        next();
    }
});

// main.js

async function fetchUserInfo() {
    const token = localStorage.getItem('token'); // 从本地存储中获取 Token
    if (!token) {
        console.log('未登录');
        return;
    }

    try {
        const res = await axios.get('http://localhost:9190/v1/user/info', {
            headers: {
                Authorization: token // 携带 Token 到请求头
            }
        });

        const userInfo = res.data.data;
        console.log('当前登录用户:', userInfo);

        // 可选：缓存用户信息到 localStorage
        localStorage.setItem('user', JSON.stringify(userInfo));

    } catch (error) {
        console.error('获取用户信息失败:', error);
    }
}

fetchUserInfo(); // 调用函数获取用户信息




app.mount('#app')